package com.hzsd.zengbanyi.biaodan_text.Actrivity;


import android.annotation.SuppressLint;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.hzsd.zengbanyi.biaodan_text.BaseActivity;
import com.hzsd.zengbanyi.biaodan_text.R;
import com.hzsd.zengbanyi.biaodan_text.bean.Sample;
import com.hzsd.zengbanyi.biaodan_text.bean.SamplePointLog;
import com.hzsd.zengbanyi.biaodan_text.bean.WorkDAO;
import com.hzsd.zengbanyi.biaodan_text.interfaces.InterfaceCallback;
import com.hzsd.zengbanyi.biaodan_text.view.TraverseControl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;


public class EditSampleActivity extends BaseActivity implements OnClickListener {

    private static final String TAG = "EditSampleActivity";
    /**
     * 签字参数
     */
    private String sUrl = "http://192.168.0.48:8888/Demo/DefaulServlet";
    private String signatureField1 = "signatureField1";
    private String signatureField2 = "signatureField2";
    public String FileFolder = "hzzc";
    private String File_PATH = Environment.getExternalStorageDirectory()
            + File.separator + FileFolder + File.separator;
    protected int local_flag = LOCAL_FILE;
    private final static int LOCAL_FILE = 1;

    private EditText tvPellucidity, tvTemperature, tvO2, tvSampleLook,
            sceneMan, recordPerson;
    private TextView tvGeneralPlace, tvSampleCode, tvSamplePlace,
            tvPicAndMp4, tvAddress, tvJWD, tvQianYue, tv_StandardTitle;
    static TextView tvSampleTime;
    private TextView tv_memo;
    private Spinner tides;
    private Button btnSave, btnAdd;
    private TextView btReturn;
    private Button btn_copy;// 复制按钮
    private LinearLayout llBaseItem, llDJdingwei, ll_Standard, ll_Tide, ll_temperature;
    private View viewTide, view_Temperature;
    private RelativeLayout rl_return;
    private Sample sample;
    private String sampleId, taskId, samplePlace, sampleGeneralPlace,
            sampleCode, SampleState, deleteItem, addItem,
            taskSceneId;
    static String SampleTime;
    private String position;// 点击的是第几个排口（上个页面传过来的值）
    private String isPreservation = "0";// 是否点击了保存(0=没有，1=保存)
    private String EName;
    private WorkDAO workdao;
    private TimePickerFragment timePicker;
    private ArrayList<String> baseList, deleteList, itemList, addList,
            listViewIsContain;
    private ArrayList<SamplePointLog> samplePointLogs;
    private static int minute;
    private static int hour;
    private int singleSelectedId;
    private LocationClient locationClient = null;
    private static final int UPDATE_TIME = 5000;

    private final int requestCode = 1;

    // private static int LOCATION_COUTNS = 0;
    double lat = 0;// 纬度
    double lng = 0;// 经度
    String address;// 位置信息

    private Context context;

    private String type;
    private HashMap<String, String> hashMap = new HashMap<String, String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_sample);
        initBaseDataBundle();
        initView();
        initDB();
        StandardView();
        initCopy();
        initWz();
        initBaseData();
        this.registerForContextMenu(tvSampleLook);
    }

    private void initBaseDataBundle() {
        Bundle bundle = getIntent().getExtras();
        type = bundle.getString("type");

    }

    /**
     * 初始化界面
     */
    private void initView() {
        context = EditSampleActivity.this;
        tvQianYue = (TextView) findViewById(R.id.tv_qianzi);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        tvJWD = (TextView) findViewById(R.id.tv_jwd);
        btnAdd = (Button) findViewById(R.id.btn_add);
        btnSave = (Button) findViewById(R.id.btn_save);
        llBaseItem = (LinearLayout) findViewById(R.id.llbaseitem);
        tvGeneralPlace = (TextView) findViewById(R.id.general_place);
        tvSampleCode = (TextView) findViewById(R.id.sample_code);
        tvSamplePlace = (TextView) findViewById(R.id.sample_place);
        tvSampleTime = (TextView) findViewById(R.id.sample_time);
        tvPellucidity = (EditText) findViewById(R.id.pellucidity);
        tvTemperature = (EditText) findViewById(R.id.temperature);
        tvO2 = (EditText) findViewById(R.id.O2);
        tvSampleLook = (EditText) findViewById(R.id.sample_look);
        tides = (Spinner) findViewById(R.id.tides);
        rl_return = (RelativeLayout) findViewById(R.id.rl_return);
        tvPicAndMp4 = (TextView) findViewById(R.id.tv_duomeiti);
        btReturn = (TextView) findViewById(R.id.bt_return);
        llDJdingwei = (LinearLayout) findViewById(R.id.ll_dingwei);
        btn_copy = (Button) findViewById(R.id.btn_copy);
        sceneMan = (EditText) findViewById(R.id.scene_man);
        recordPerson = (EditText) findViewById(R.id.record_person);
        llBaseItem.setOrientation(LinearLayout.HORIZONTAL);
        tv_memo = (TextView) findViewById(R.id.tv_memo);
        tv_StandardTitle = (TextView) findViewById(R.id.tv_StandardTitle);
        ll_Standard = (LinearLayout) findViewById(R.id.ll_Standard);
        ll_Tide = (LinearLayout) findViewById(R.id.ll_Tide);
        ll_temperature = (LinearLayout) findViewById(R.id.ll_temperature);
        viewTide = findViewById(R.id.viewTide);
        view_Temperature = findViewById(R.id.view_Temperature);
        tvQianYue.setOnClickListener(this);
        llDJdingwei.setOnClickListener(this);
        tvPicAndMp4.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        rl_return.setOnClickListener(this);
        btReturn.setOnClickListener(this);
        tvSampleTime.setOnClickListener(this);
        btnSave.setOnClickListener(this);
        tv_memo.setOnClickListener(this);

        // 点击复制按钮
        btn_copy.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // String
                // spFileCopy=getSDPath()+File.separator+"data"+File.separator+"data"+File.separator+getPackageName()+File.separator+"shared_prefs"+File.separator+taskId+".xml";
                String spFileCopy = File.separator + "data" + File.separator
                        + "data" + File.separator + getPackageName()
                        + File.separator + "shared_prefs" + File.separator
                        + taskId + ".xml";
                // /data/data/hzst.startech.hjjc/shared_prefs/f49bf8af-d7b7-49e3-afb5-c23473e2ea76.xml
                /*
                 * File fe=getDir("",MODE_PRIVATE); String
				 * spFileCopy=fe+File.separator+taskId+".xml";
				 */
                if (CopyfileIsExists(spFileCopy)) {
                    SharedPreferences sp = getSharedPreferences(taskId,
                            MODE_PRIVATE);
                    String tvSampleLookCpoy = sp.getString("tvSampleLook", "");
                    String tidesCpoy = sp.getString("tides", "");
                    String tvPellucidityCopy = sp
                            .getString("tvPellucidity", "");
                    String tvTemperatureCopy = sp
                            .getString("tvTemperature", "");
                    String tvO2Copy = sp.getString("tvO2", "");
                    tvSampleLook.setText(tvSampleLookCpoy);
                    tvPellucidity.setText(tvPellucidityCopy);
                    tvTemperature.setText(tvTemperatureCopy);
                    tvO2.setText(tvO2Copy);
                    switch (tidesCpoy) {
                        case "涨":
                            tides.setSelection(1);
                            break;
                        case "退":
                            tides.setSelection(2);
                            break;
                        default:
                            tides.setSelection(0);
                            break;
                    }
                } else {
                    Toast.makeText(EditSampleActivity.this,
                            "无法复制,您的第一个样品信息没有保存或不是同类型！", Toast.LENGTH_SHORT)
                            .show();
                }

            }

        });
        // samplesLook.setOnItemSelectedListener(new OnItemSelectedListener() {
        // @Override
        // public void onItemSelected(AdapterView<?> parent, View view,
        // int position, long id) {
        // SampleFace=parent.getItemAtPosition(position).toString();
        // }
        // @Override
        // public void onNothingSelected(AdapterView<?> parent) {
        // }
        // });
        tides.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                SampleState = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        //
        // IntentFilter filter = new IntentFilter(
        // "com.kinggrid.iapppdf.broadcast.savepdf");
        // registerReceiver(receiver, filter);
        // Settings.System.putInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION,
        // 0);
    }

    public InterfaceCallback.TextChangeCallback textChangeCallback;

    public InterfaceCallback.TextChangeCallback getTextChangeCallback() {
        return textChangeCallback;
    }

    public void setTextChangeCallback(InterfaceCallback.TextChangeCallback textChangeCallback) {
        this.textChangeCallback = textChangeCallback;
    }

    /**
     * 排污口或现场水文 视图
     */
    private void StandardView() {
        if ("污染源".equals(type)) {
            ll_Tide.setVisibility(View.GONE);
            ll_temperature.setVisibility(View.GONE);
            viewTide.setVisibility(View.GONE);
            view_Temperature.setVisibility(View.GONE);
            tv_StandardTitle.setText("排污口");
        } else {
            tv_StandardTitle.setText("现场水文");

        }
        //循环生成控件（现场水文/排污口）
        TraverseControl traverseControl = new TraverseControl(context);
        traverseControl.getView(ll_Standard, type, sampleId);


        //这里使用接口回调 循环控件的值（现场水文/排污口）
        InterfaceCallback callback = new InterfaceCallback();
        callback.setTextChangeCallback(new InterfaceCallback.TextChangeCallback() {

            @Override
            public void getTextChange(String key, String text) {
                hashMap.put(key, text);//将填写的值存放在HashMap 中

            }
        });

    }

    private void initBaseData() {
        samplePointLogs = new ArrayList<SamplePointLog>();
        samplePointLogs = workdao.getsample(sampleId);

    }

    /**
     * 判断采样地点GPS误差，超出误差填写日志说明
     */
    private void GPSErrorLog() {
        if (samplePointLogs.size() > 0) {
            if (lat == 0 || lng == 0) {
                Builder builder = new Builder(
                        EditSampleActivity.this);
                builder.setTitle("提示");
                builder.setMessage("数据无法保存，获取GPS定位失败，请移动到开阔地！");
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {

                            }
                        });
                builder.create().show();
                return;
            }
            final double prelng = Double.parseDouble(samplePointLogs.get(0)
                    .getPrePointX());
            final double prelat = Double.parseDouble(samplePointLogs.get(0)
                    .getPrePointY());
            LatLng reallatLng = new LatLng(lat, lng);
			/*
			 * double prelat = 30.256145; double prelng = 120.621358;
			 */
            LatLng prelatLng = new LatLng(prelat, prelng);
            final double distance = DistanceUtil.getDistance(reallatLng,
                    prelatLng);// 得出两点之间的距离
            if (distance > 10) {
                // 误差超出10米，需写日志说明
                Builder builder = new Builder(
                        EditSampleActivity.this);
                builder.setTitle("提示");
                builder.setMessage("系统检测到你的位置与预定位置不符，是否保存？");
                builder.setPositiveButton("保存",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                samplePointLogs.get(0).setMemo(
                                        "理论坐标：（" + prelng + "，" + prelat
                                                + "）与实际坐标：（" + lng + "，" + lat
                                                + "）相隔" + distance + "米");
                                samplePointLogs.get(0).setCreateTime(
                                        getCurrentTime());
                                samplePointLogs.get(0).setRealPointX(lng + "");
                                samplePointLogs.get(0).setRealPointY(lat + "");
                                samplePointLogs.get(0).setTask_id(taskId);
                                samplePointLogs.get(0).setSample_id(sampleId);
                                samplePointLogs.get(0).setSample_code(
                                        sampleCode);
                                if (workdao.addSamplePoint_Log(samplePointLogs)) {
                                    // Toast.makeText(EditSampleActivity.this,
                                    // "日志已保存", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(EditSampleActivity.this,
                                            "日志保存失败", Toast.LENGTH_SHORT)
                                            .show();
                                }
                                save();
                            }
                        });
                builder.setNegativeButton("不保存",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                // TODO Auto-generated method stub
                            }
                        });
                builder.setCancelable(false);
                builder.create().show();
            } else {
                save();
            }

        } else {
            save();
			/*
			 * Toast.makeText(EditSampleActivity.this, "数据库中找不到预定位置数据信息",
			 * Toast.LENGTH_SHORT).show();
			 */
        }

    }

    /**
     * 此功能已废除
     */
    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        switch (arg0) {
            case requestCode:
                if (RESULT_OK == arg1) {
                    String gpslog = arg2.getStringExtra("gpslog");
                    if (samplePointLogs.size() > 0) {
                        samplePointLogs.get(0).setMemo(gpslog);
                        samplePointLogs.get(0).setCreateTime(getCurrentTime());
                        samplePointLogs.get(0).setRealPointX(lng + "");
                        samplePointLogs.get(0).setRealPointY(lat + "");
                        samplePointLogs.get(0).setTask_id(taskId);
                        samplePointLogs.get(0).setSample_id(sampleId);
                        samplePointLogs.get(0).setSample_code(sampleCode);
                        if (workdao.addSamplePoint_Log(samplePointLogs)) {
                            Toast.makeText(EditSampleActivity.this, "日志已保存",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(EditSampleActivity.this, "日志保存失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                break;

            default:
                break;
        }
    }

    /**
     * 格式化当前时间
     *
     * @return
     */
    public String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return sdf.format(System.currentTimeMillis());

    }

    /**
     * 复制按钮是否可见（第一个样品信息中不可见，其他可见）
     */
    private void initCopy() {
        if (!"0".equals(position)) {
            btn_copy.setVisibility(btn_copy.VISIBLE);
        } else {
            btn_copy.setVisibility(btn_copy.GONE);
        }

    }

    /**
     * 初始化定位信息
     */
    private void initWz() {
        locationClient = new LocationClient(getApplicationContext());
        // 设置定位条件
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationMode.Hight_Accuracy);// 设置定位模式
        option.setOpenGps(true); // 是否打开GPS
        option.setCoorType("bd09ll"); // 设置返回值的坐标类型。

        // option.setPriority(LocationClientOption.NetWorkFirst); //设置定位优先级
        option.setProdName("LocationDemo"); // 设置产品线名称。
        option.setScanSpan(UPDATE_TIME); // 设置定时定位的时间间隔。单位毫秒
        option.setIsNeedAddress(true);// 返回的定位结果包含地址信息
        locationClient.setLocOption(option);

        // 注册位置监听器
        locationClient.registerLocationListener(new BDLocationListener() {

            @Override
            public void onReceiveLocation(BDLocation location) {
                // TODO Auto-generated method stub
                if (location == null) {
                    return;
                }

                StringBuffer sb = new StringBuffer(256);
                // sb.append("Time : ");
                // sb.append(location.getTime());
                // sb.append("\nError code : ");
                // sb.append(location.getLocType());
                // sb.append("\nLatitude : ");
                // sb.append(location.getLatitude());//纬度
                lat = location.getLatitude();
                // sb.append("纬度："+lat);
                // sb.append("\nLontitude : ");
                // sb.append(location.getLongitude());//经度
                lng = location.getLongitude();
                // sb.append("\n经度："+lng+"\n");
                // sb.append("\nRadius : ");
                // sb.append(location.getRadius());
                if (location.getLocType() == BDLocation.TypeGpsLocation) {
                    // sb.append("\nSpeed : ");
                    // sb.append(location.getSpeed());
                    // sb.append("\nSatellite : ");
                    // sb.append(location.getSatelliteNumber());
                    sb.append(location.getAddrStr());// 位置信息
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                    sb.append(location.getAddrStr());// 位置信息
                }
                lat = get2Double(lat);
                lng = get2Double(lng);
                if (lat == 0 || lng == 0) {
                    tvAddress.setVisibility(View.GONE);
                } else {
                    tvAddress.setVisibility(View.VISIBLE);
                }
                tvAddress.setText("位置信息：" + sb.toString());
                tvJWD.setText("经度：" + lng + "，纬度：" + lat);
                System.out.println("经度：" + lng + "，纬度：" + lat);
                System.out.println("位置信息：" + sb.toString());
                System.out.println("定位错误码：" + location.getLocType());
                // locationInfoTextView.setText(address);
            }

            public void onReceivePoi(BDLocation location) {

            }

        });
        locationClient.start();
        // locationClient.requestLocation();
		/*
		 * if (locationClient == null) return ; if (locationClient.isStarted()){
		 * locationClient.stop();
		 * 
		 * } else{ locationClient.start(); }
		 */

    }

    public static double get2Double(double a) {
        DecimalFormat df = new DecimalFormat("0.000000");
        return new Double(df.format(a).toString());
    }

    @Override
    protected void onStop() {
        if (locationClient != null && locationClient.isStarted()) {
            locationClient.stop();
            // locationClient = null;
        }
        super.onStop();
    }

    @Override
    protected void onResume() {
        if (locationClient != null && !locationClient.isStarted()) {
            locationClient.start();
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (locationClient != null && locationClient.isStarted()) {
            locationClient.stop();
            locationClient = null;
        }
        // unregisterReceiver(receiver);
        super.onDestroy();
    }

    /**
     * 初始化数据信息
     */
    @SuppressLint("SimpleDateFormat")
    private void initDB() {
        try {
            copyAssetsFileToSDCard("new.pdf", File_PATH + "newPDF.pdf");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            // Log.d("Kevin", "error : " + e.toString());
        }
        SharedPreferences share = getSharedPreferences("user", MODE_PRIVATE);
        sampleId = share.getString("sampleId", "");
        taskId = share.getString("taskId", "");
        taskSceneId = share.getString("taskSceneId", "");

        sampleGeneralPlace = share.getString("sampleGeneralPlace", "");
        samplePlace = share.getString("samplePlace", "");
        sampleCode = share.getString("sampleCode", "");
        EName = share.getString("EName", "");
        position = share.getString("position", "");

        deleteList = new ArrayList<String>();
        addList = new ArrayList<String>();
        listViewIsContain = new ArrayList<String>();
        workdao = new WorkDAO(this);
        //设置采样时间
        getSampleTime(sampleId);
        tvSampleTime.setText(SampleTime.substring(SampleTime.indexOf(" ") + 1, SampleTime.lastIndexOf(":")));

        Sample sample2 = workdao.GetSampleDetail(sampleId);
        baseList = workdao.GetBaseItem(taskId, sampleId);
        listViewIsContain.addAll(baseList);
        itemList = workdao.GetAllBaseItem();
        DeleteBaseItem deleteBaseItem = new DeleteBaseItem();
        for (int i = 0; i < baseList.size(); i++) {
            TextView tv = new TextView(this);
            LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            tv.setBackgroundResource(R.drawable.btn_del2);
            tv.setGravity(Gravity.CENTER);
            tv.setTextSize(20);
            tv.setTextColor(getResources().getColor(android.R.color.black));
            lp.rightMargin = 5;
            tv.setLayoutParams(lp);
            tv.setText(baseList.get(i));
            tv.setClickable(true);
            llBaseItem.setGravity(Gravity.CENTER_VERTICAL);
            llBaseItem.addView(tv);
            tv.setOnClickListener(deleteBaseItem);
        }
        tvO2.setText(sample2.oxygen);
        tvPellucidity.setText(sample2.tmd);
        tvTemperature.setText(sample2.temperature);
        switch (sample2.sampleState) {
            case "涨":
                tides.setSelection(1);
                break;
            case "退":
                tides.setSelection(2);
                break;
            default:
                tides.setSelection(0);
                break;
        }

        tvSampleLook.setText(sample2.sampleFace);
        tvGeneralPlace.setText(sampleGeneralPlace);
        tvSampleCode.setText(sampleCode);
        tvSamplePlace.setText(samplePlace);
        sceneMan.setText(sample2.sceneMan);
        recordPerson.setText(sample2.recordPerson);

    }

    /**
     * 获取采样时间
     * 1.获取数据库中的采样时间
     * 2.如果数据库中没有时间，则获取当前时间
     *
     * @param sampleID
     * @return
     */
    public void getSampleTime(String sampleID) {
        String sampleTime = workdao.getSampleStartTime(sampleID);
        if ("".equals(sampleTime)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            SampleTime = dateFormat.format(Calendar.getInstance().getTime());
        } else {
            SampleTime = sampleTime;
        }

    }

    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        }
        return sdDir.toString();

    }

    /***
     * 判断存放复制内容的文件是否存在
     */
    public boolean CopyfileIsExists(String file) {
        try {
            File f = new File(file);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        menu.add("清、无色");
        menu.add("黑、浑浊");
        menu.add("褐色、清");
        menu.add("白色、浑浊");
        menu.add("白色、清");
        menu.add("红色、浑浊");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        tvSampleLook.setText(item.getTitle());
		/*if ("清、无色".equals(item.getTitle())) {
			tvSampleLook.setText("清、无色");
		} else if ("黑、浑浊".equals(item.getTitle())) {
			tvSampleLook.setText("黑、浑浊");
		} else if ("褐色、清".equals(item.getTitle())) {
			tvSampleLook.setText("褐色、清");
		} else if ("白色、浑浊".equals(item.getTitle())) {
			tvSampleLook.setText("白色、浑浊");
		}*/
        return true;
    }

    /**
     * 显示时间选择器
     */
    public void showTimePickerDialog(View view) {
        timePicker = new TimePickerFragment();
        timePicker.show(getSupportFragmentManager(), "timePicker");
    }

    public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar calendar = Calendar.getInstance();
            hour = calendar.get(Calendar.HOUR_OF_DAY);
            minute = calendar.get(Calendar.MINUTE);

            return new TimePickerDialog(getActivity(), this, hour, minute, true);
        }

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            String hour = hourOfDay < 10 ? "0" + hourOfDay : hourOfDay + "";
            String min = minute < 10 ? "0" + minute : minute + "";
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd ");
            String ymd = dateFormat.format(new Date());
            SampleTime = ymd + hour + ":" + min + ":00";
            tvSampleTime.setText(SampleTime.substring(SampleTime.indexOf(" ") + 1, SampleTime.lastIndexOf(":")));

        }
    }

    /**
     * 删除对话框
     *
     * @author Yyang
     */
    class DeleteBaseItem implements OnClickListener {
        @Override
        public void onClick(View v) {
            deleteDialog(v);

        }
    }

    private void deleteDialog(final View v) {
        Builder builder = new Builder(
                EditSampleActivity.this);
        builder.setTitle("你确定删除吗");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                TextView tv = (TextView) v;
                tv.setVisibility(View.GONE);
                deleteItem = tv.getText().toString();
                deleteList.add(deleteItem);
                listViewIsContain.remove(deleteItem);
                Toast.makeText(EditSampleActivity.this, "删除成功",
                        Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

            }
        });
        builder.create().show();
    }

    private void AddDialog() {

        singleSelectedId = -1;
        Builder builder = new Builder(
                EditSampleActivity.this);
        builder.setTitle("请选择你要添加的项目");
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                EditSampleActivity.this, android.R.layout.simple_list_item_1,
                itemList);
        builder.setSingleChoiceItems(adapter, singleSelectedId,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        singleSelectedId = which;
                    }
                });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (singleSelectedId >= 0) {
                    addItem = itemList.get(singleSelectedId);
                    if (listViewIsContain.contains(addItem)) {
                        Toast.makeText(EditSampleActivity.this, "不能添加相同项目",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        addList.add(addItem);
                        listViewIsContain.add(addItem);
                        buildTextViewItem(singleSelectedId);
                        Toast.makeText(EditSampleActivity.this,
                                "添加" + addItem + "成功", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }

    /**
     * 动态建立基础栏目界面
     *
     * @param i
     */
    private void buildTextViewItem(int i) {
        DeleteBaseItem deleteBaseItem = new DeleteBaseItem();
        TextView tv = new TextView(this);
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        tv.setBackgroundResource(R.drawable.btn_del2);
        tv.setGravity(Gravity.CENTER);
        tv.setTextSize(20);
        tv.setTextColor(getResources().getColor(android.R.color.black));
        lp.rightMargin = 5;
        tv.setLayoutParams(lp);
        tv.setText(itemList.get(i));
        tv.setClickable(true);
        llBaseItem.setGravity(Gravity.CENTER_VERTICAL);

        llBaseItem.addView(tv);
        tv.setOnClickListener(deleteBaseItem);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.ll_dingwei:
                intent = new Intent(EditSampleActivity.this, DituActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_duomeiti:
                intent = new Intent(EditSampleActivity.this, MedioActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_memo:// 此功能已废除
                if (workdao.getsample(sampleId).size() > 0) {
                    intent = new Intent(EditSampleActivity.this,
                            GpsErrorLogActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("sampleId", sampleId);
                    bundle.putBoolean("force", false);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, requestCode);
                } else {
                    Toast.makeText(EditSampleActivity.this, "数据库中找不到预定位置数据信息",
                            Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.btn_add:
                AddDialog();
                break;
            case R.id.rl_return:
                finish();
                break;
            case R.id.bt_return:
                finish();
                break;
            case R.id.sample_time:
                showTimePickerDialog(v);
                break;
            case R.id.btn_save:
                GPSErrorLog();
                SaveMarks();
                break;
            case R.id.tv_qianzi:
                String filepath;
                if (fileIsExists()) {
                    filepath = File_PATH + taskSceneId + ".pdf";
                } else {
                    filepath = File_PATH + "newPDF.pdf";
                }
                SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit(); // �༭�ļ�
                edit.putString("filepath", filepath);
                edit.commit();

                GOTOPDF(filepath);

                // workdao.addSignatureImgPath(File_PATH +taskSceneId+".bmp",
                // taskSceneId);

                break;
        }
    }

    /**
     * 保存痕迹
     */
    public void SaveMarks() {

    }

    /**
     * 保存页面填写数据到数据库
     */
    public void save() {
		/*SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy/MM/dd ");
		String date = sDateFormat.format(new java.util.Date());*/
        sample = new Sample();
        sample.sampleStartTime = SampleTime;
        sample.sampleFace = tvSampleLook.getText().toString();
        sample.sampleState = SampleState;
        sample.tmd = tvPellucidity.getText().toString();
        sample.temperature = tvTemperature.getText().toString();
        sample.oxygen = tvO2.getText().toString();
        sample.sampleId = sampleId;
        for (int i = 0; i < addList.size(); i++) {
            workdao.addBaseItem(addList.get(i), taskId, sampleId);

        }
        for (int i = 0; i < deleteList.size(); i++) {
            workdao.deleteBaseItem(deleteList.get(i), taskId, sampleId);

        }
        workdao.updateSample(sample);
        saveStandard();
        // 保存痕迹
        sample.taskSceneId = taskSceneId;
        sample.createtime = getCurrentTime();
        workdao.getSampletime(sample);
        // sample = workdao.SelectSample(sample);
        workdao.addSampleMark(sample);
        // 这里是复制功能所需要保存的值
        if ("0".equals(position)) {
            SharedPreferences sp = getSharedPreferences(taskId, MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("tvSampleLook", tvSampleLook.getText().toString());
            editor.putString("tides", SampleState);
            editor.putString("tvPellucidity", tvPellucidity.getText()
                    .toString());
            editor.putString("tvTemperature", tvTemperature.getText()
                    .toString());
            editor.putString("tvO2", tvO2.getText().toString());
            editor.commit();
            // Toast.makeText(EditSampleActivity.this,"复制完毕！",
            // Toast.LENGTH_SHORT).show();
        }
        Toast.makeText(EditSampleActivity.this, "保存成功", Toast.LENGTH_SHORT)
                .show();
    }

    public boolean fileIsExists() {
        try {
            File f = new File(File_PATH + taskSceneId + ".pdf");
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
        return true;
    }

    private void GOTOPDF(String filepath) {
        // File file = new File(filepath);
        // final Uri uri = Uri.fromFile(file);
        //
        // Log.v(TAG, "uri = " + uri.getPath());
        // final Intent intent = new Intent("android.intent.action.VIEW", uri);
        // /*intent.setClassName("com.kinggrid.iapppdf.demo",
        // "com.kinggrid.iapppdf.demo.BookShower");*/
        // intent.setClassName(getApplicationContext(),
        // "com.kinggrid.iapppdf.demo.BookShower");
        // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // Log.v(TAG, "username = " + userName);
        // if (userName.getText().toString() == null || sureCopyRight() == null)
        // {
        // return;
        // }
        //
        // intent.putExtra("sUrl", sUrl.getText().toString());
        // intent.putExtra("userName", userName.getText().toString());
        // intent.putExtra("signatureField1",
        // signatureField1.getText().toString());
        // intent.putExtra("signatureField2",
        // signatureField2.getText().toString());
        // intent.putExtra("copyRight", sureCopyRight());
        //
        // intent.putExtra("isCanField_edit", chv_canFieldEdit.isChecked());
        // intent.putExtra("isVectorSign", chv_isVectorSign.isChecked());
        // intent.putExtra("isAnnotProtect", chv_isAnnotProtect.isChecked());
        // intent.putExtra("isSupportEbenT7Mode", sureModes());
        // intent.putExtra("saveVector", false);
        // if (chv_fillTemplate.isChecked()) {
        // intent.putExtra("template", sureFillTemplate());
        // }
        //
        // Bundle bundle = new Bundle();
        // bundle.putParcelable("pageViewMode", surePageViewMode());
        // intent.putExtras(bundle);
        // intent.putExtra("local_flag", local_flag);
        // if (local_flag == WEB_FILE) {
        // intent.putExtra("weburl", url.getText().toString());
        // }
        //
        // intent.putExtra("bookRotation",
        // ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // startActivity(intent);
        File file = new File(filepath);
        final Uri uri = Uri.fromFile(file);

        Log.v(TAG, "uri = " + uri.getPath());
        final Intent intent = new Intent("android.intent.action.VIEW", uri);
        intent.setClassName(getApplicationContext(),
                "hzst.startech.hjjc.activity.BookShower");
        // intent.setClass(EditSampleActivity.this,BookShower.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // TODO Auto-generated catch block

        String copyRight = "SxD/phFsuhBWZSmMVtSjKZmm/c/3zSMrkV2Bbj5tznTbalOoU/SoNEHp4A/HvseYNfrq0k/tYu9aiVnc45auDzHJ9ymw8oH48HggOjYvytC/M6iAKDk2CYDvnU/qVpSow1Lyf/gCcnnf/q/UnniWd073/v12IkrJrHbDJVKS5FJwgmOThQp8xrADhCx0m3Vm4qE3BpMNjVZfdPNXM5iqz53ypMrnEAwwOzZZo9SKIPMuiv2lLV+jXsHRW/NsP++8DUqxZZmH/65o+Uabdko83B4kpCz9EoJSPc8Cuy1KJPRDBVzCuEF2kzvFyN13lwGf/FVKwAIpWNNINn5h/pqNg2pz6EtSWBWc8nNFKZOtJR3bKKY1jBInFPtwonbBivMLmUM5O23DX/hk5qFeybmnOnz6nJbuvVI7AN8ok9vFBwmgvIjq2wPLlRWrgXxzyRenBDgtWtF8gXeygZH6AMf67lOGDCZOU830usJDIcG344o=";

        intent.putExtra("sUrl", sUrl);
        intent.putExtra("userName", EName);
        intent.putExtra("signatureField1", signatureField1);
        intent.putExtra("signatureField2", signatureField2);
        intent.putExtra("copyRight", copyRight);

        intent.putExtra("isCanField_edit", false);
        intent.putExtra("isVectorSign", false);
        intent.putExtra("isAnnotProtect", false);
        intent.putExtra("isSupportEbenT7Mode", false);
        intent.putExtra("saveVector", false);

        Bundle bundle = new Bundle();

        intent.putExtras(bundle);
        intent.putExtra("local_flag", local_flag);

        intent.putExtra("bookRotation", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        startActivity(intent);
    }

    private void copyAssetsFileToSDCard(String fileName, String toFilePath)
            throws IOException {
        File file = new File(toFilePath);
        if (file.exists()) {
            return;
        }
        InputStream myInput;
        OutputStream myOutput = new FileOutputStream(toFilePath);
        Log.d("Kevin", "fileName : " + fileName);
        myInput = getAssets().open(fileName);
        Log.d("Kevin", "getAssets ");
        byte[] buffer = new byte[1024];
        int length = myInput.read(buffer);
        while (length > 0) {
            myOutput.write(buffer, 0, length);
            length = myInput.read(buffer);
        }
        myOutput.flush();
        myInput.close();
        myOutput.close();
    }

    private List<HashMap<String, String>> getData(String filePath) {
        List<HashMap<String, String>> filedata = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> filehashMap;
        File file = new File(filePath);
        if (file.isDirectory()) {
            File[] fileArray = file.listFiles(new FileNameSelector(
                    "pdf||.pdf||.PDF"));
            if (null != fileArray && 0 != fileArray.length) {
                for (int i = 0; i < fileArray.length; i++) {
                    if (!fileArray[i].isDirectory()) {
                        filehashMap = new HashMap<String, String>();
                        filehashMap.put("filename", fileArray[i].getName()
                                .toString());
                        filehashMap.put("url", fileArray[i].getPath());
                        Log.v(TAG, "file path = " + fileArray[i].getPath()
                                + "file name = " + fileArray[i].getName());
                        filedata.add(filehashMap);
                    }
                }
            }

        }

        return filedata;
    }

    public class FileNameSelector implements FilenameFilter {
        String extension = ".";

        public FileNameSelector(String fileExtensionNoDot) {
            extension += fileExtensionNoDot;
        }

        @Override
        public boolean accept(File dir, String name) {

            return name.endsWith("pdf") || name.endsWith("PDF");
        }
    }

    /**
     * 保存 现场水文/排污口数据
     */
    public void saveStandard() {
        String typeValue;
        if ("污染源".equals(type)) {
            typeValue = "污染源废水";
        } else {
            typeValue = "地表水";

        }
        Iterator iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry entry = (Entry) iterator.next();

            workdao.updataStandard(sampleId, (String) entry.getKey(), (String) entry.getValue(), typeValue);
        }


    }
}
